#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
批量修复Lombok @Slf4j注解问题
将@Slf4j注解替换为手动Logger定义

@author cencat
@since 2024
"""

import os
import re

def fix_slf4j_in_file(file_path):
    """修复单个文件中的@Slf4j注解"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 检查是否包含@Slf4j
        if '@Slf4j' not in content:
            return False
        
        print(f"正在修复文件: {file_path}")
        
        # 替换import语句
        content = re.sub(
            r'import lombok\.extern\.slf4j\.Slf4j;',
            'import org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;',
            content
        )
        
        # 查找类名
        class_match = re.search(r'public class (\w+)', content)
        if not class_match:
            print(f"  警告: 无法找到类名，跳过文件 {file_path}")
            return False
        
        class_name = class_match.group(1)
        
        # 替换@Slf4j注解
        # 处理单独一行的@Slf4j
        content = re.sub(
            r'^@Slf4j\s*$',
            '',
            content,
            flags=re.MULTILINE
        )
        
        # 处理与其他注解在同一行的@Slf4j
        content = re.sub(
            r'@Slf4j\s+(@\w+)',
            r'\1',
            content
        )
        
        # 在类定义后添加Logger定义
        class_pattern = r'(public class ' + re.escape(class_name) + r'[^{]*\{)'
        logger_definition = f'\n\n    private static final Logger log = LoggerFactory.getLogger({class_name}.class);'
        
        content = re.sub(
            class_pattern,
            r'\1' + logger_definition,
            content
        )
        
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(content)
        
        print(f"  ✓ 修复完成: {file_path}")
        return True
        
    except Exception as e:
        print(f"  ✗ 修复失败: {file_path}, 错误: {e}")
        return False

def find_java_files(directory):
    """查找所有Java文件"""
    java_files = []
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file.endswith('.java'):
                java_files.append(os.path.join(root, file))
    return java_files

def main():
    """主函数"""
    # 项目根目录
    project_root = r'c:\Users\岑小刚\Desktop\my-cencat\cencat-common\src'
    
    print("开始批量修复@Slf4j注解问题...")
    print(f"扫描目录: {project_root}")
    
    # 查找所有Java文件
    java_files = find_java_files(project_root)
    print(f"找到 {len(java_files)} 个Java文件")
    
    # 修复每个文件
    fixed_count = 0
    for java_file in java_files:
        if fix_slf4j_in_file(java_file):
            fixed_count += 1
    
    print(f"\n修复完成! 共修复了 {fixed_count} 个文件")
    print("请重新编译项目以验证修复结果")

if __name__ == '__main__':
    main()